package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AddressDao;
import com.itheima.dao.OrderDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地址信息管理功能
 */
@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private OrderDao orderDao;

    //添加地址信息
    @Override
    public void addAddress(Address address) {
        addressDao.addAddress(address);
        //获取自增的ID值
        Integer addressId = address.getId();
        //查询与address关联的order中的id，并添加到中间表中
        String telephone = address.getTelephone();
        Integer orderId = orderDao.findByOrderId(telephone);
        //创建map用于存储id
        Map map=new HashMap<>();
        map.put("addressId",addressId);
        map.put("orderId",orderId);
        addressDao.addOrderByAddressId(map);
    }
//分页查询
    @Override
    public PageResult findpage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage,pageSize);
        String queryString = queryPageBean.getQueryString();
        Map map=new HashMap<>();
        map.put("queryString",queryString);
        Page<Address> page=addressDao.findQuery(map);
        return new PageResult(page.getTotal(),page.getResult());
    }
//回写数据
    @Override
    public Address copyback(Integer id) {
        Address address=addressDao.copyback(id);
        return address;
    }
//编辑检查组
    @Override
    public void editAddress(Address address) {
        addressDao.editAddress(address);
    }
//删除地址数据 + 关联关系
    @Override
    public void deleteAddress(Integer id) {
        //查询order_id
//        Integer orderid=orderDao.findByID(id);
        //先删除关系表
        addressDao.deleteAddressByorder(id);
        //删除地址表数据
        addressDao.deleteAddress(id);
    }
//查询预约地址
    @Override
    public List<Address> findAddress() {
        List<Address> addresses=addressDao.findAddress();
        return addresses;
    }
}
